<template>
  <el-tabs v-model="activeName">
    <el-tab-pane label="菜单设置" name="first">
      <el-row>
        <div class="menu-view">
          <div class="iphone">
            <img src="./iphone_head.png" class="iphone_head" alt="">
            <div class="iphone_content">
              <ul class="menu" ref="menuList">
                <li v-for="(item , index) in menuData" class="menu-btn">
                  <div v-if="item.sub_button.length > 0" class="btns">
                    <a href="javascript:" @click="menuIndex($event,index)">{{item.name}}</a>
                    <ul class="menu-btn">
                      <li class="menu-btnList" v-if="item.sub_button.length != 0">
                        <a href="javascript:" @click="menuIndex($event,index , n )"
                           v-for="(i , n) in item.sub_button">{{i.name}}</a>
                      </li>
                      <li class="menu-childAdd" @click="menuAddChild(index)"><span>+</span></li>
                      <li class="sj"></li>
                    </ul>
                  </div>
                  <div v-else class="btns">
                    <a href="javascript:" @click="menuIndex($event,index)">{{item.name}}</a>
                    <ul class="menu-btn">
                      <li class="menu-childAdd" @click="menuAddChild(index)"><span>+</span></li>
                      <li class="sj"></li>
                    </ul>
                  </div>
                </li>
                <li class="menu-add" @click="menuAdd()" v-if="menuData.length <= 2"><span>+</span>
                </li>
              </ul>
            </div>
            <div class="iphone-footer"></div>
          </div>
        </div>
        <div class="menu-input">
          <div class="menu-page">
            <el-card class="box-card">
              <div slot="header" class="clearfix" style="position: relative">
                <span>菜单设置</span>
                <el-popover style="top: 0;right: 210px;position: absolute"
                            placement="top"
                            width="160"
                            v-model="visible2">
                  <p>删除该主菜单，相关子菜单也会同时删除，确定要删除吗？</p>
                  <div style="text-align: right; margin: 0">
                    <el-button size="mini" type="text" @click="visible2 = false">取消</el-button>
                    <el-button type="primary" size="mini" @click="mainMenuRemove()">确定</el-button>
                  </div>
                </el-popover>
                <span style="position: absolute; top: 0; right: 0;cursor: pointer"
                      @click="menuRemoveColumn()">X</span>
              </div>
              <div class="menu-data">
                <el-input placeholder="菜单标题，不超过16个字节，子菜单不超过40个字节,一汉字等于两字节，一字母等于一个字节"
                          v-model="currentMenuData.name">
                  <template slot="prepend">菜单名称</template>
                </el-input>
                <div v-if="menuHide" class="menu-from">
                  <div class="menu-type clearfix">
                    <span class="tilte">子菜单内容</span>
                    <div class="content">
                      <el-radio v-model="currentMenuData.type" label="click">点击推事件</el-radio>
                      <el-radio v-model="currentMenuData.type" label="view">网页跳转</el-radio>
                      <!--<el-radio v-model="currentMenuData.type" label="miniprogram">小程序跳转</el-radio>-->
                      <!--<el-radio v-model="currentMenuData.type" label="scancode_waitmsg">扫码带提示</el-radio>-->
                      <!--<el-radio v-model="currentMenuData.type" label="scancode_push">扫码推事件</el-radio>-->
                      <!--<el-radio v-model="currentMenuData.type" label="pic_sysphoto">系统拍照发图</el-radio>-->
                      <!--<el-radio v-model="currentMenuData.type" label="pic_photo_or_album">拍照或者相册发图</el-radio>-->
                      <!--<el-radio v-model="currentMenuData.type" label="pic_weixin">微信相册发图</el-radio>-->
                      <!--<el-radio v-model="currentMenuData.type" label="location_select">发送位置</el-radio>-->
                    </div>
                  </div>
                  <div class="menu-val" v-if="currentMenuData.type === 'view'">
                    <p class="tip">
                      订阅者点击该子菜单会跳到以下链接 ( 链接格式：http://www.baidu.com/ )
                    </p>
                    <el-input placeholder="请输入内容" v-model="currentMenuData.url">
                      <template slot="prepend">页面地址</template>
                    </el-input>
                  </div>
                  <div class="menu-val" v-if="currentMenuData.type === 'click'">
                    <p class="tip">
                      请输入已经设置好的自定义回复的匹配规则！
                    </p>
                    <label style="font-size: 14px;margin-right: 10px">匹配规则</label>
                    <el-autocomplete
                      popper-class="my-autocomplete"
                      v-model="currentMenuData.key"
                      :fetch-suggestions="querySearch"
                      placeholder="请输入内容"
                      @select="handleSelect">
                      <i
                        class="el-icon-edit el-input__icon"
                        slot="suffix"
                        @click="handleIconClick">
                      </i>
                      <template slot-scope="props">
                        <div class="name">名称：{{ props.item.title }}</div>
                        <span class="addr">key：{{ props.item.menuKey }}&nbsp;&nbsp;类型：{{ props.item.type }}</span>
                      </template>
                    </el-autocomplete>
                  </div>
                  <p class="tip" style="color: #fd6969">
                    该项为必填项，如果没填，会导致菜单创建失败！
                  </p>
                </div>
              </div>
            </el-card>
            <el-card class="box-card" style="margin-top:20px ">
              <div slot="header" class="clearfix">
                <span>个性化菜单</span>
                <el-switch
                  v-model="individuationMenu"
                  active-color="#409eff"
                  inactive-color="#ff4949"
                  active-text="开启个性化菜单">
                </el-switch>
              </div>
              <div class="menu-data">
                <div v-if="!individuationMenu">
                  <p class="tip">
                    为了帮助公众号实现灵活的业务运营，微信公众平台新增了个性化菜单接口，开发者可以通过该接口，让公众号的不同用户群体看到不一样的自定义菜单。
                  </p>
                  <p class="tip" style="margin-top: 10px">
                    1、创建个性化菜单之前必须先创建默认菜单（默认菜单是指使用普通自定义菜单创建接口创建的菜单）。如果删除默认菜单，个性化菜单也会全部删除
                  </p>
                  <p class="tip" style="margin-top: 10px">
                    2、个性化菜单要求用户的微信客户端版本在iPhone6.2.2，Android 6.2.4以上，暂时不支持其他版本微信
                  </p>
                </div>
                <div v-if="individuationMenu">
                  <p class="tip">
                    开启个性化菜单后一下选项至上填入一项，否则会创建失败！
                  </p>
                  <div class="menu-from">
                    <div class="menu-type clearfix">
                      <span class="tilte">用户标签</span>
                      <div class="content">
                        <el-cascader
                          :options="tagList"
                          v-model="tagVal"
                          change-on-select>
                        </el-cascader>
                      </div>
                    </div>
                    <div class="menu-type clearfix">
                      <span class="tilte">性别</span>
                      <div class="content">
                        <el-radio v-model="matchrule.sex" label="">全部</el-radio>
                        <el-radio v-model="matchrule.sex" label="1">男</el-radio>
                        <el-radio v-model="matchrule.sex" label="2">女</el-radio>
                      </div>
                    </div>
                    <div class="menu-type clearfix">
                      <span class="tilte">客户端版本</span>
                      <div class="content">
                        <el-radio v-model="matchrule.client_platform_type" label="">全部</el-radio>
                        <el-radio v-model="matchrule.client_platform_type" label="1">IOS</el-radio>
                        <el-radio v-model="matchrule.client_platform_type" label="2"> Android</el-radio>
                        <el-radio v-model="matchrule.client_platform_type" label="3"> Others</el-radio>
                      </div>
                    </div>
                    <div class="menu-type clearfix">
                      <span class="tilte">地区</span>
                      <div class="content">
                        <el-cascader
                          :options="cityOptions"
                          v-model="cityVal"
                          change-on-select>
                        </el-cascader>
                      </div>
                    </div>
                    <div class="menu-type clearfix">
                      <span class="tilte">语言</span>
                      <div class="content">
                        <el-cascader
                          :options="language"
                          v-model="languageVal"
                          change-on-select>
                        </el-cascader>
                      </div>
                    </div>
                  </div>
                </div>
                <div style="margin-top: 20px ;text-align: center">
                  <el-button type="primary" @click="menuSubmit()">提交</el-button>
                </div>
              </div>
            </el-card>
          </div>
        </div>
      </el-row>
    </el-tab-pane>
    <el-tab-pane label="菜单管理" name="second">
      <div style="padding-right: 15px">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>菜单管理</span>
            <p class="tip">如需修改菜单点击查看后重新编辑，再删除原来的菜单！</p>
          </div>
          <template>
            <div ref="menuViewList">
              <el-table
                :data="menuDataList"
                style="width: 100%">
                <el-table-column
                  prop="id"
                  label="菜单id">
                </el-table-column>
                <el-table-column
                  prop="menuType"
                  label="菜单类型">
                </el-table-column>
                <el-table-column
                  prop="menuid"
                  label="操作">
                  <template slot-scope="scope">
                    <el-button @click="viewMenu(scope.row)" type="text" size="small">查看</el-button>
                    <el-button @click="visible3 = true;confirm = removeMenu.bind({}, scope.row, scope.$index)"
                               type="text"
                               size="small">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <el-popover style="top: 20%;right: 55%;position: fixed;z-index:9999;"
                        placement="top"
                        width="160"
                        v-model="visible3">
              <p>确认要删除该菜单吗？如果该菜单为基础菜单，所有个性化菜单也会被删除！（删除个性化菜单不会对其它菜单有影响）</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="visible3 = false">取消</el-button>
                <el-button type="primary" size="mini" @click="visible3 = false;confirm()">确定</el-button>
              </div>
            </el-popover>
          </template>
        </el-card>
      </div>
    </el-tab-pane>
  </el-tabs>
</template>
<script>
  import cityOptions from './city_data2017_element.js'

  export default {
    data() {
      return {
        visible2: false, // 删除菜单栏提示
        visible3: false, // 删除菜单提示
        menuDataList: [], // 菜单管理列表
        activeName: 'first', // 菜单管理，菜单设置second切换
        cityOptions: cityOptions, // 地区json
        tagList: [], // 标签列表
        language: [
          {
            'value': '2',
            'label': '简体中文'
          },
          {
            'value': '3',
            'label': '繁体中文TW'
          },
          {
            'value': '4',
            'label': '繁体中文HK '
          },
          {
            'value': '5',
            'label': '英文 '
          },
          {
            'value': '6',
            'label': '印尼'
          },
          {
            'value': '7',
            'label': '马来'
          },
          {
            'value': '8',
            'label': '西班牙'
          },
          {
            'value': '9',
            'label': '韩国'
          },
          {
            'value': '10',
            'label': '意大利 '
          },
          {
            'value': '11',
            'label': '日本'
          },
          {
            'value': '12',
            'label': '波兰'
          },
          {
            'value': '13',
            'label': '葡萄牙 '
          },
          {
            'value': '14',
            'label': '俄国'
          },
          {
            'value': '15',
            'label': '泰文'
          },
          {
            'value': '16',
            'label': '越南'
          },
          {
            'value': '17',
            'label': '阿拉伯语'
          },
          {
            'value': '18',
            'label': '北印度'
          },
          {
            'value': '19',
            'label': '希伯来'
          },
          {
            'value': '20',
            'label': '土耳其'
          },
          {
            'value': '21',
            'label': '德语'
          },
          {
            'value': '21',
            'label': '法语'
          }
        ], // 语言列表
        cityVal: [], // 地区选择值
        languageVal: [], // 语言选中值
        tagVal: [], // 标签选择值
        width: 0, // 主菜单宽度
        menuHide: true, // 主菜单是否有子菜单  true 为无子菜单
        individuationMenu: false, // 是否开启个性化菜单
        getMenuBoolean: true, // 避免重复获取菜单列表
        menuSubmitBoolean: false, // 避免重复提交菜单
        menuI: 0,
        menuN: 0,
        currentMenuData: {
          'type': '',
          'name': '',
          'key': '',
          'url': '',
          'appid': '',
          'pagepath': '',
          'media_id': ''
        },
        menuData: [
          {
            'type': 'click',
            'name': '菜单名称',
            'key': '',
            'url': '',
            'appid': '',
            'pagepath': '',
            'media_id': '',
            'sub_button': []
          }
        ],
        matchrule: {
          'tag_id': '',
          'sex': '',
          'country': '',
          'province': '',
          'city': '',
          'client_platform_type': '',
          'language': ''
        },
        restaurants: [] // 回复菜单key值列表
      }
    },
    mounted() {
      let _self = this
      _self.setWidth()
      let aList = this.$refs.menuList.getElementsByTagName('a')
      if (_self.menuData[0].sub_button.length > 0) {
        aList[1].style.border = '1px solid #86E020'
        _self.currentMenuData = _self.menuData[_self.menuI].sub_button[_self.menuN]
      } else {
        _self.menuN = undefined
        aList[0].style.border = '1px solid #86E020'
        _self.currentMenuData = _self.menuData[_self.menuI]
      }
      // 获取tagList
      _self.$ajax.post('/weChat/tagList', {}).then(function (response) {
        if (response.data.code === 0) {
          for (let i = 0; response.data.data.length > i; i++) {
            _self.tagList.push({
              'value': response.data.data[i].tag[0].id,
              'label': response.data.data[i].tag[0].name
            })
          }
        } else {
          _self.$message('获取标签信息失败，无法个性化菜单无法设置标签组，请刷新重试！')
        }
      }).catch(function (error) {
        console.log(error)
      })
      // 获取key值列表
      _self.$ajax.get('/weChat/replyList').then(function (response) {
        if (response.data.code === 0) {
          _self.restaurants = response.data.textDataList
        } else {
          _self.$message('获取回复列表失败，请刷新重试！')
        }
      }).catch(function (error) {
        console.log(error)
      })
    },
    methods: {
      // 提交菜单
      menuSubmit() {
        let _self = this
        if (_self.menuSubmitBoolean) {
          return
        }
        _self.menuSubmitBoolean = true
        if (!_self.individuationMenu) {
          _self.$ajax.post('/weChat/createMenu', {data: {button: _self.menuData}}).then(function (response) {
            _self.menuSubmitBoolean = false
            if (response.data.code === 0) {
              _self.$message('创建自定义菜单成功')
              _self.activeName = 'second'
              _self.getMenuBoolean = true
            } else {
              _self.$message('创建自定义菜单失败！')
            }
          }).catch(function (error) {
            _self.menuSubmitBoolean = false
            console.log(error)
          })
        } else {
          _self.$ajax.post('/weChat/IndividualizationMenu', {
            data: {
              button: _self.menuData,
              matchrule: _self.matchrule
            }
          }).then(function (response) {
            _self.menuSubmitBoolean = false
            if (response.data.code === 0) {
              _self.$message('创建个性化菜单成功！')
              _self.activeName = 'second'
              _self.getMenuBoolean = true
            } else {
              _self.$message('创建个性化菜单失败！')
            }
          }).catch(function (error) {
            console.log(error)
          })
        }
      },
      // 移除某一个菜单栏
      menuRemoveColumn() {
        if (this.menuN === undefined) {
          try {
            if (this.menuData[this.menuI].sub_button.length > 0) {
              this.visible2 = true
            } else {
              this.menuData.splice(this.menuI, 1)
            }
          } catch (err) {
          }
        } else {
          this.menuData[this.menuI].sub_button.splice(this.menuN, 1)
        }
      },
      mainMenuRemove() {
        this.visible2 = false
        this.menuData.splice(this.menuI, 1)
      },
      // i 为主菜单号位 n为子菜单号位  获取当前菜单位置
      menuIndex(e, i, n) {
        let aList = this.$refs.menuList.getElementsByTagName('a')
        let currentA = e.target
        for (let m = 0; aList.length > m; m++) {
          aList[m].style.border = '1px solid #e0e0e0'
        }
        currentA.style.border = '1px solid #86E020'
        this.menuN = n
        this.menuI = i
        this.menuSelected()
      },
      menuSelected() {
        if (this.menuN === undefined) {
          this.currentMenuData = this.menuData[this.menuI]
          if (this.menuData[this.menuI].sub_button.length > 0) {
            this.menuHide = false
          } else {
            this.menuHide = true
          }
        } else {
          this.currentMenuData = this.menuData[this.menuI].sub_button[this.menuN]
          this.menuHide = true
        }
      },
      // 添加子菜单
      menuAddChild(index) {
        let menuDataBtn = this.menuData[index].sub_button
        if (menuDataBtn.length > 4) {
          return
        }
        menuDataBtn.push({
          'type': 'click',
          'name': '子菜单名称',
          'key': '',
          'url': '',
          'appid': '',
          'pagepath': '',
          'media_id': '',
          'sub_button': []
        })
      },
      // 添加主菜单
      menuAdd() {
        let menuDatt = this.menuData
        if (menuDatt.length > 2) {
          return
        }
        menuDatt.push({
          'type': 'click',
          'name': '菜单名称',
          'key': '',
          'url': '',
          'appid': '',
          'pagepath': '',
          'media_id': '',
          'sub_button': []
        })
      },
      // 设置主菜单宽度
      setWidth() {
        let menuList = this.$refs.menuList.children
        let width = 280 / menuList.length
        for (let i = 0; menuList.length > i; i++) {
          menuList[i].style.width = width + 'px'
        }
      },
      // 菜单管理部分js
      // 查看菜单详情
      viewMenu(data) {
        this.activeName = 'first'
        let aList = this.$refs.menuList.getElementsByTagName('a')
        for (let m = 0; aList.length > m; m++) {
          aList[m].style.border = '1px solid #e0e0e0'
        }
        aList[0].style.border = '1px solid #86E020'
        this.menuN = undefined
        this.menuI = 0
        this.menuData = data.button
        if (data.matchrule) {
          for (let key in data.matchrule) {
            this.matchrule[key] = data.matchrule[key]
          }
          this.individuationMenu = true
        }
        this.menuSelected()
      },
      removeMenu(menu, index) {
        console.info(menu)
        let _self = this
        let menuType = ''
        let menuid = ''
        // 1 为自定义菜单 0为个性化菜单
        if (!menu.matchrule) {
          menuType = 1
        } else {
          menuType = 0
          menuid = menu.menuid
        }
        _self.$ajax.post('/weChat/removeMenu', {menuType: menuType, menuid: menuid}).then(function (response) {
          _self.$message(response.data.msg)
          if (index === 0) {
            _self.menuDataList = []
          } else {
            _self.menuDataList.splice(index, 1)
          }
        }).catch(function (error) {
          console.log(error)
        })
      },
      // 菜单匹配规则
      querySearch(queryString, cb) {
        var restaurants = this.restaurants
        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
        // 调用 callback 返回建议列表的数据
        cb(results)
      },
      createFilter(queryString) {
        return (restaurant) => {
          return (restaurant.menuKey.toLowerCase().indexOf(queryString.toLowerCase()) >= 0)
        }
      },
      handleSelect(item) {
        this.currentMenuData.key = item.menuKey
      },
      handleIconClick(ev) {
        console.log(ev)
      }
    },
    watch: {
      activeName() {
        let _self = this
        if (_self.getMenuBoolean) {
          _self.getMenuBoolean = false
          // 获取菜单列表
          _self.$ajax.get('/weChat/getMenu', {}).then(function (response) {
            if (response.data.code === 0) {
              _self.menuDataList = []
              let menuData = response.data.menuData.conditionalmenu
              _self.menuDataList.push({
                'menuType': '基础菜单',
                'menuid': response.data.menuData.menu.menuid,
                'id': 1,
                'button': response.data.menuData.menu.button
              })
              for (let i = 0; menuData.length > i; i++) {
                _self.menuDataList.push({
                  'menuType': '个性化菜单',
                  'menuid': '',
                  'id': '',
                  'button': ''
                })
                _self.menuDataList[i + 1]['id'] = i + 2
                _self.menuDataList[i + 1]['menuid'] = menuData[i].menuid
                _self.menuDataList[i + 1]['button'] = menuData[i].button
                _self.menuDataList[i + 1]['matchrule'] = menuData[i].matchrule
              }
            } else {
              _self.$message('获取菜单信息失败！请勿一直刷新重试！')
            }
          }).catch(function (error) {
            console.log(error)
          })
        }
      },
      cityVal() {
        if (this.cityVal.length === 1) {
          this.matchrule.province = this.cityVal[0]
          this.matchrule.city = '中国'
          this.matchrule.country = ''
        } else {
          this.matchrule.country = this.cityVal[1]
        }
      },
      languageVal() {
        this.matchrule.language = this.languageVal[0]
      },
      tagVal() {
        this.matchrule.tag_id = this.tagVal[0]
      },
      menuData() {
        this.$nextTick(() => {
          this.setWidth()
        })
      },
      currentMenuData() {
        try {
          this.menuData[this.menuI].sub_button[this.menuN] = this.currentMenuData
        } catch (err) {
          this.menuData[this.menuI] = this.currentMenuData
        }
      }
    }
  }
</script>
<style lang="less">
  .el-autocomplete{
    width: 400px;
  }
  .my-autocomplete {
    width: 400px;
    li {
      line-height: normal;
      padding: 7px;
      .name {
        text-overflow: ellipsis;
        overflow: hidden;
      }
      .addr {
        font-size: 12px;
        color: #b4b4b4;
      }

      .highlighted .addr {
        color: #ddd;
      }
    }
  }
  .el-tabs, .el-tabs__content, .el-tab-pane, .el-row {
    width: 100%;
  }

  .menu-input {
    float: left;
    overflow: hidden;
    width: 100%;
    .menu-page {
      margin-left: 350px;
      word-wrap: break-word;
      padding: 20px;
      /*padding: 200px;*/
      box-sizing: border-box;
      .menu-type {
        margin-top: 20px;
        span.tilte {
          font-size: 14px;
          margin-right: 15px;
          float: left;
          height: 40px;
          line-height: 40px;
        }
        div.content {
          float: left;
          line-height: 40px;
        }
      }
      .menu-val {
        margin-top: 20px;
        p {
          margin-bottom: 10px;
        }
      }
    }
  }

  .menu-view {
    width: 350px;
    margin-right: -100%;
    float: left;
  }

  .iphone {
    border: 1px solid #e0e0e0;
    border-radius: 30px;
    width: 300px;
    text-align: center;
    background-color: #fff;
    .iphone_head {
      margin: 10px 0;
    }
    .iphone_content {
      width: 280px;
      margin: 0 auto;
      border: 1px solid #e0e0e0;
      height: 400px;
      background: url("./titlebar.png") no-repeat;
      -webkit-background-size: 100% auto;
      background-size: 100% auto;
      position: relative;
      .menu {
        background-color: #fbfbfb;
        width: 100%;
        position: absolute;
        bottom: 0;
        left: 0;
        .menu-add, & > li.menu-btn {
          height: 38px;
          line-height: 38px;
          border-left: 1px solid #e0e0e0;
          display: inline-block;
          float: left;
          box-sizing: border-box;
          a, span {
            border-top: 1px solid #e0e0e0;
            display: inline-block;
            width: 100%;
            height: 100%;
            color: #333;
            overflow: hidden;
            display: -webkit-box;
            -webkit-line-clamp: 1;
            -webkit-box-orient: vertical;
            font-size: 14px;
            cursor: pointer;
          }
        }
        .menu-add {
          a, span {
            cursor: pointer;
            font-size: 28px;
            color: #999;
          }
        }
        & > li.menu-btn {
          &:nth-child(1) {
            border-left: none;
          }
          div.btns {
            position: relative;
            width: 99%;
            height: 100%;
            .menu-btn {
              position: absolute;
              background-color: #fbfbfb;
              bottom: 55px;
              left: 50%;
              margin-left: -42px;
              li.menu-btnList, .menu-childAdd {
                width: 280/3-12px;
                border: 1px solid #e0e0e0;
                a, span {
                  cursor: pointer;
                  border: 1px solid #e0e0e0;
                  height: 38px;
                  line-height: 38px;
                }
              }
              .menu-childAdd {
                a, span {
                  cursor: pointer;
                  font-size: 28px;
                  color: #999;
                }
              }
              .sj {
                z-index: 99;
                content: "";
                width: 0;
                height: 0;
                border: 10px solid #e0e0e0;
                border-left-color: transparent;
                border-right-color: transparent;
                border-bottom-color: transparent;
                position: absolute;
                bottom: -19px;
                left: 50%;
                margin-left: -10px;
              }
            }
          }
        }
      }
    }
    .iphone-footer {
      height: 50px;
      width: 50px;
      border: 1px solid #e0e0e0;
      border-radius: 100%;
      display: inline-block;
      margin: 10px 0;
    }
  }
</style>
